package com.zhang.learnnacos.app1.controller;

import com.zhang.learnnacos.api.app2.IUserInterFace;
import com.zhang.learnnacos.api.app2.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhanghaolian
 * @date 2021/5/9 15:19
 */
@RestController
@Slf4j
@RefreshScope
public class App1Controller {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${spring.application.name}")
    private String appName;

    @Value("${aaa.bb}")
    private String aa;

    @Value("${aaa.cc}")
    private String bb;

    @Autowired
    private IUserInterFace userInterFace;

    @PostMapping("/user/add")
    public String addUser(UserDto user) {
        log.error(aa);
        log.error(bb);
        log.info("addUser:{}", user);
        int i = userInterFace.addUser(user);
        if (i == 1) {
            return "success";
        }
        return "fail";
    }

    @GetMapping(value = "/echo/{string}")
    public String echo(@PathVariable String string) {
        return "Hello Nacos Discovery " + string;
    }

    @GetMapping("/echo/app-name")
    public String echoAppName() {
        //Access through the combination of LoadBalanceClient and RestTemplate
        ServiceInstance serviceInstance = loadBalancerClient.choose("app1");
        discoveryClient.getInstances("app1");
        String path = String.format("http://%s:%s/echo/%s", serviceInstance.getHost(), serviceInstance.getPort(), appName);
        System.out.println("request path:" + path);
        return restTemplate.getForObject(path, String.class);
    }

}